package com.csaba.connector.citi.model;

import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.cookie.Cookie;
import org.apache.http.message.BasicNameValuePair;

import com.csaba.connector.ServiceException;
import com.csaba.connector.citi.parser.CitiCodes;
import com.csaba.connector.web.util.WebSession;

public class CitiSession extends WebSession implements WebSession.RedirectHandler
{
	private static final long serialVersionUID = 8151459956093974170L;

	public final static boolean DEBUG_FILE = false; //FIXME set to false
	public final static String DEBUG_FILE_PATH = "../citi.source/";

	public final static boolean DEBUG_COOKIE = true; //FIXME set to false	

	public CitiSession()
	{
		super();
		setBank(CitiBank.getInstance());
		if ( DEBUG_FILE )
			setDebugFilePath("../citi.source/");
		setUserAgent(CitiRequestFactory.MOZILLA);
		setDebugCookies(DEBUG_COOKIE);
	}

	/**
	 * Create a TimeStamp at end of URL. 
	 * Where it is needed, it is signed with TS_NEEDED text in name of URL string.
	 * @return with the current time (String) e.g.: "1222431063308"
	 */
	private String getTimeStamp()
	{
		final Date date = new Date();
		final Long time = date.getTime();
		return time.toString();
	}

	public String doGetWithTimeStamp( final String url ) throws ServiceException
	{
		return doGet(url + getTimeStamp());
	}

	public final NameValuePair getCookieValue( final String cookieName )
	{
		final List<Cookie> cookies = client.getCookieStore().getCookies();
		NameValuePair nameValuePair = null;
		if ( cookies != null )
		{
			for ( final Cookie cookie : cookies )
			{
				if ( cookie.equals(cookie.getName()) )
				{
					nameValuePair = new BasicNameValuePair(cookie.getName(), cookie.getValue());
					break;
				}
			}
		}
		return nameValuePair;
	}

	public final boolean isSessionIDAvailable()
	{
		return getCookieValue(CitiCodes.JSESSIONID) != null;
	}

	@Override
	public String redirectedTo( String url )
	{
		if ( !url.startsWith(CitiRequestFactory.HOMEBANK_URL_BASE) && url.startsWith("/") )
		{
			url = CitiRequestFactory.HOMEBANK_URL_BASE + url;
		}
		return url;
	}

}
